package cn.quang.search.toolkit.component.groups.impl;

import cn.quang.search.toolkit.component.ISearch;
import cn.quang.search.toolkit.component.groups.AbstractSearchGroup;
import cn.quang.search.toolkit.enums.DataSourceTypeEnum;
import cn.quang.search.toolkit.enums.SearchLogicType;
import cn.quang.search.toolkit.enums.SearchOperator;
import cn.quang.search.toolkit.provider.entity.QuerySlice;

import java.util.Collections;
import java.util.List;

/**
 * 默认的SearchGroup
 * 该SearchGroup支持MySQL和ES通用的查询操作符，比如：
 * =, >=, <=, <>, is null, is not null, in, not in 等
 */
public class SearchGroup extends AbstractSearchGroup {

    public SearchGroup(DataSourceTypeEnum dsType, SearchLogicType logicType) {
        super(dsType, logicType);
    }

    public void addSearch(String field, SearchOperator operator, Object value) {
        this.addSearch(searchItemFactory.getSearch(field, operator, value));
    }

    public void addCustomSearch(String conditionSql){
        this.addSearch(searchItemFactory.getCustomSearch(conditionSql));
    }

    public void addGeoSearch(String field, double longitude, double latitude, String distinct) {
        this.addSearch(searchItemFactory.getGeoSearch(field, longitude, latitude, distinct));
    }

    public void addNestedSearch(String field, ISearch key, ISearch value) {
        this.addNestedSearch(field, key, value == null ? null : Collections.singletonList(value));
    }

    public void addNestedSearch(String field, ISearch key, List<ISearch> values) {
        this.addSearch(searchItemFactory.getNestedSearch(field, key, values));
    }

    public <T> void addBetweenSearch(String col, Object fromValue, Object toValue){
        this.addSearch(searchItemFactory.getBetweenSearch(col, fromValue, toValue));
    }

    public static void main(String[] args) {
        SearchGroup a = new SearchGroup(DataSourceTypeEnum.ES, SearchLogicType.OR);

        SearchGroup searchGroup = new SearchGroup(DataSourceTypeEnum.ES, SearchLogicType.AND);
        searchGroup.addSearch("libraryId", SearchOperator.In, new Integer[]{5});
        // 针对CURRENT_STAGE特殊处理 ： 因为渠道progress字段通过「<」查询更快
        searchGroup.addSearch("currentStage", SearchOperator.LessThan, "1.0");
        searchGroup.addSearch("bindingType", SearchOperator.In, new Integer[]{0, 12060});
        searchGroup.addSearch("oppStatus", SearchOperator.In, new Integer[]{0, 4});

        a.addSearchGroup(searchGroup);

        SearchGroup b = new SearchGroup(DataSourceTypeEnum.ES, SearchLogicType.OR);
        b.addSearch("testB", SearchOperator.Equal, "b");
        b.addSearch("testC", SearchOperator.In, new String[]{"b", "c", "d"});

        a.addSearchGroup(b);

        QuerySlice querySlice = a.getQuerySlice();
        System.out.println(querySlice.getSqlTemplate());
        System.out.println(querySlice.getKeyOperatorValues());
    }
}
